package pl.edu.agh.lab2.sr.gameServer;

import java.rmi.RemoteException;
import java.util.Random;

import pl.edu.agh.lab2.sr.beans.Field;
import pl.edu.agh.lab2.sr.beans.GameMap;
import pl.edu.agh.lab2.sr.beans.GameResponses;
import pl.edu.agh.lab2.sr.beans.IPlayer;
import pl.edu.agh.lab2.sr.beans.Player;
import pl.edu.agh.lab2.sr.beans.ServerListener;
import pl.edu.agh.lab2.sr.remoteInterfaces.IBattleshipGame;
import pl.edu.agh.lab2.sr.remoteInterfaces.IServerListener;

public class BattleshipBotPlayer implements Runnable {

	private IPlayer player;
	private IServerListener listener;
	private IBattleshipGame game;
	private Random rand;

	public BattleshipBotPlayer(String nick) throws RemoteException {
		super();
		this.player = new Player(nick);
		this.listener = new ServerListener();
		this.rand = new Random(System.currentTimeMillis());
	}

	public void setGame(IBattleshipGame game) {
		this.game = game;
	}

	public IPlayer getPlayer() {
		return player;
	}

	public IServerListener getListener() {
		return listener;
	}

	@Override
	public void run() {
		System.out.println("[B] started bot thread");
		System.out.println("[B] initializing map");
		GameMap map = new GameMap();
		map.initMyMapWithSampleShips(player.getNick().length());
		try {
			game.initMap(player, map);
		} catch (Exception e) {
			System.err.println("[B] error initializing map: " + e);
			System.exit(2);
		}
		GameResponses lastResponse;
		while (true) {
			try {
				Thread.sleep(5000);
				do {
					lastResponse = game.move(player, getNextField());
				} while (lastResponse == GameResponses.AlreadyShooted
						|| lastResponse == GameResponses.HittedShip);

				if (lastResponse == GameResponses.GameFinished) {
					System.out.println("[B]" + player.getNick()
							+ " Game finished. Exiting");
					System.exit(0);
				}
				System.out.println("[B]" + player.getNick() + " response: "
						+ lastResponse);

			} catch (Exception e) {
				System.err.println("[B]" + player.getNick() + " error: " + e);
			}
		}
	}

	private Field getNextField() {
		char x = (char) ('A' + rand.nextInt(10));
		int y = 1 + rand.nextInt(10);
		Field filed = new Field(x, y);
		return filed;

	}

}
